<template>
  <div>{{ value }}
    <div v-if="uploadType=='file'">
      <div class="uploadList">
        <div v-if="fileList.length < limit" style="margin-bottom: 10px;">
          <el-upload
            v-bind="$attrs" 
            v-model="value" 
            ref="uploader"
            :action="uploadUrl"
            :headers="headers"
            :limit="limit"
            :accept="accept"
            name="file"
            :multiple="multiple"
            :before-upload="handleBeforeUpload"
            :on-success="handleUploadSuccess"
            :on-error="handleError"
            :on-remove="handleRemove"
            :show-file-list="false"
            :file-list="fileList"
          >
            <el-button type="primary" :icon="icon">{{  title }}</el-button>
          </el-upload>
        </div>
        <div class="item" v-for="(item,index) in fileList" :key="index">
          <div class="upload-images success" :style="style">
            <i class="jd-icon" :class="getFileIcon(item)" style="font-size:60px"/>
            <el-icon-download class="preview" @click="handleDownLoad(item)"/>
            <el-icon-delete class="delete" @click="handleRemove(item)"/>
          </div>
        </div>
      </div>
    </div>
    <div v-else>
      <div class="uploadList">
        <div class="item" v-for="(item,index) in fileList" :key="index">
          <div class="upload-images success" :style="style">
            <img :src="item.url" style="max-width:100%; margin: 0px auto">
            <el-icon-view class="preview" @click="handlePreview(item)"/>
            <el-icon-delete class="delete" @click="handleRemove(item)"/>
          </div>
        </div>
        <div class="item" v-if="fileList.length < limit">
          <el-upload
            ref="uploader"
            v-bind="$attrs" 
            v-model="value" 
            :action="uploadUrl"
            :headers="headers"
            :limit="limit"
            :accept="accept"
            name="file"
            :multiple="multiple"
            :before-upload="handleBeforeUpload"
            :on-success="handleUploadSuccess"
            :on-remove="handleRemove"
            :show-file-list="false"
            :file-list="fileList"
          >
            <div class="upload-images" :style="style">
              <el-icon-plus class="icon"/>
            </div>
          </el-upload>
        </div>
      </div>
      <div class="upload-tips" v-if="showTips && fileList.length < limit">{{ tips }}</div>
      <el-dialog v-model="dialogVisible" title="图片预览" width="800">
        <img :src="dialogImageUrl" alt="" style="display:block; max-width:100%; margin:0px auto"/>
      </el-dialog>
    </div>
  </div>
</template>
<script>
  import { defineAsyncComponent } from "vue";
  import { genFileId } from "element-plus";
  import config from "@/config/upload";

  import sysConfig from "@/config";
  import tool from '@/utils/tool';

  export default {
    props: {
      modelValue: { type: String, default: "" },
      showTips: { type: Boolean, default: true },
      tips: { type: String, default: "请上传大小不超过10MB，格式为 doc/xls/ppt/pdf的文件" },
      uploadType: {type: String, default: "file"},
      width: { type: Number, default: 100 },
      height: { type: Number, default: 100 },
      title: { type: String, default: "选取附件" },
      icon: { type: String, default: "el-icon-upload" },
      multiple: { type: Boolean, default: false },
      action: { type: String, default: "" },
      name: { type: String, default: config.filename },
      data: { type: Object, default: () => {} },
      accept: { type: String, default: "application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.template,application/pdf,application/x-zip-compressed" },
      maxSize: { type: Number, default: config.maxSizeFile },
      limit: { type: Number, default: 1 },
      onSuccess: {
        type: Function,
        default: () => {
          return true
        }
      },
    },
    data() {
      return {
        number: 0,
        value: "",
        file: null,
        style: {
          width: this.width + "px",
          height: this.height + "px"
        },
        uploadList: [],
        uploadUrl: process.env.VUE_APP_API_URL + "/file/upload",
        headers:{
          "Authorization": sysConfig.TOKEN_PREFIX + tool.cookie.get("TOKEN")
        },
        fileList: [],
        dialogImageUrl: '',
        dialogVisible: false,
      }
    },
    computed:{
			value: function(){
				return this.$attrs.modelValue;
			}
		},
    watch: {
      modelValue(val) {
        this.value = val
      },
      value(val) {
        this.$emit("update:modelValue", val)
      }
    },
    mounted() {
      this.value = this.modelValue
    },
    methods: {
      // 获取文件图标
      getFileIcon(file){
        var icon = "icon-unknown";
        var fileExt = file.name.substring(file.name.lastIndexOf(".")+1);
        if (fileExt!=""){
          icon = "icon-"+ fileExt;
        }
        console.log('icon',icon)
        return icon;
      },
      handleError(err) {
        this.$notify.error({
          title: "上传文件未成功",
          message: err
        })
      },
      // 上传前Loading加载
      handleBeforeUpload(file){
        const acceptIncludes = this.accept.replace(/\s/g, "").split(",").includes(file.type)
        if (!acceptIncludes) {
          var message = "选择的文件非文件类型，允许的格式：doc/docx/xls/ppt/pdf/zip";
          if (this.uploadType=="image"){ 
            message = "选择的文件非图像类文件，允许的格式：jpg/png";
          }
          this.$notify.warning({
            title: "上传文件警告",
            message: message
          })
          return false;
        }
        const maxSize = file.size / 1024 / 1024 < this.maxSize
        if (!maxSize) {
          this.$message.warning(`上传文件大小不能超过 ${this.maxSize}MB!`)
          return false
        }
        this.number++;
      },
      // 文件上传成功
      handleUploadSuccess(res){
        this.uploadList.push({ name: res.data.name, url:res.data.url});
        if (this.uploadList.length === this.number){
          this.fileList = this.fileList.concat(this.uploadList);
          this.uploadList = [];
          this.number = 0;
          this.value = this.fileList;
        }
      },
      // 删除文件
      handleRemove(file){
        const findex = this.fileList.map(f=>f.name).indexOf(file.name);
        if (findex > -1){
          this.fileList.splice(findex, 1);
          this.value = this.fileList;
        }
      },
      // 预览图片
      handlePreview(file){
        this.dialogVisible = true;
        this.dialogImageUrl = file.url;
      },
      // 下载文件
      handleDownLoad(file){
        const a = document.createElement('a');
        a.href = file.url;
        a.target = '_blank';
        a.download = file.name;
        a.click();
      },
    }
  }
</script>
<style lang="scss" scoped>
.uploadList{
  .item{
    float: left;
    position: relative;
    width:100px;
    height:100px;
    margin-right: 10px;
  }
}
.upload-images{
  position: relative;
  width:100px;
  height:100px;
  line-height: 100px;
  text-align: center;
  border:1px dashed #dcdfe6;
  border-radius: 6px;
  overflow: hidden;
  cursor: pointer;

  .icon{
    position:absolute;
    width: 28%;
    height: 28%;
    top: calc((100% - 28%)/2);
    left:calc((100% - 28%)/2);
    color:#909399;
  }
}
.upload-images:hover{
  border:1px dashed #1989fa;

  .preview{
    position:absolute;
    width: 26px;
    height: 26px;
    top: calc((100% - 26px)/2);
    left:calc((100% - 26px)/2);
    color:#1989fa;
  }
  .delete{
    position:absolute;
    width: 16px;
    height: 16px;
    top: 4px;
    right: 4px;
    color:#1989fa;
    cursor: pointer;
  }
}
.upload-tips{
  padding-top: 5px;
  clear: both;
  color: #606266;
}

.fileName{
  width:100px;
  height: 30px;
  line-height: 30px;
  overflow:hidden;
  white-space:nowrap;
  text-overflow:ellipsis;
}
</style>